package pers.cfeng.server.utils;

import java.nio.ByteBuffer;
import java.util.Arrays;

/**
 * @author Cfeng
 * NIO文件的字节缓冲区Buffer
 */

public class ByteBufferParser {
    //将short放在2空间的Byte[]中
    public static byte[] short2Byte(short value) {
        return ByteBuffer.allocate(Short.SIZE/Byte.SIZE).putShort(value).array();
    }

    //将2size的buffer转为Short
    public static short parseShort(byte[] buffer) {
        ByteBuffer buf = ByteBuffer.wrap(buffer,0, 2);
        return buf.getShort();
    }

    //将int转为buffer的byte数组，都需要SIZE转换
    public static byte[] int2Byte(int value) {
        return ByteBuffer.allocate(Integer.SIZE/Byte.SIZE).putInt(value).array();
    }

    public static int parseInt(byte[] buf) {
        ByteBuffer buffer = ByteBuffer.wrap(buf, 0 , 4);
        return buffer.getInt();
    }

    public static byte[] long2Byte(long value) {
        return ByteBuffer.allocate(Long.SIZE/Byte.SIZE).putLong(value).array();
    }

    public static long parseLong(byte[] buf) {
        ByteBuffer buffer = ByteBuffer.wrap(buf,0,8);
        return buffer.getLong();
    }

    public static ParseStringRes parseString(byte[] raw) {
        int length = parseInt(Arrays.copyOf(raw, 4));
        String str = new String(Arrays.copyOfRange(raw, 4, 4+length));
        return new ParseStringRes(str, length+4);
    }

    //String转为Buffer的时候结构是String.len + String 的byte[]
    public static byte[] string2Byte(String str) {
        byte[] len = int2Byte(str.length());
        byte[] data = str.getBytes();
        //合并byte数组，利用System的arraycopy()
        return mergeBytes(len, data);
    }

    //合并字节数组
    public static byte[] mergeBytes(byte[]... arrays) {
        int totalLength = 0;
        for (byte[] array : arrays) {
            totalLength += array.length;
        }

        byte[] mergedArray = new byte[totalLength];
        int destPos = 0;

        for (byte[] array : arrays) {
            System.arraycopy(array, 0, mergedArray, destPos, array.length);
            destPos += array.length;
        }

        return mergedArray;
    }


    //字符串加密方法: 字符串转为byte数组，res = res * seed + byte
    public static long str2Uid(String key) {
        long seed = 13331;
        long res = 0;
        for(byte b : key.getBytes()) {
            res = res * seed + (long)b;
        }
        return res;
    }
}
